<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/page/include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>选择视频</title>
    <link href="${ctxStatic}/layui-v2.2.45/layui/css/layui.css" rel="stylesheet"/>
    <link rel="stylesheet" href="${ctx}/css/common/common.css">
    <link href="${ctxStatic}/video-js/video-js.min.css" rel="stylesheet">
    <link href="${ctx}/css/ui/resource/selVideo.css" rel="stylesheet"/>
    <script src="${ctxStatic}/video-js/video.min.js"></script>
    <style type="text/css">
        .video-js {
            width: 100%;
        }

        .vjs-paused .vjs-big-play-button,
        .vjs-paused.vjs-has-started .vjs-big-play-button {
            display: block !important;
        }

        .video-js .vjs-time-control {
            display: block !important;
        }

        .video-js .vjs-remaining-time {
            display: none !important;
        }

        .video-js.vjs-playing .vjs-tech {
            pointer-events: auto !important;
        }
    </style>
</head>
<body>
<div class="sel-img-panel">
    <div class="upload-content">
        <form id="form">
            <input type="file" id="upload_input" class="u-single-file dn" accept="video/mp4" multiple>
        </form>
        <button class="layui-btn layui-btn-danger" id="upload_btn">本地上传</button>
        <span class="infos gray">点击视频为播放，点击名称为选中</span>
        <div class="upload-list-content" style="display: none">
            <ul class="upload-list" id="progress_list">
            </ul>
        </div>
    </div>
    <hr class="panel-split">
    <div class="list-content sel-ctn">
        <ul class="img-list">
        </ul>
    </div>
</div>
<script type="text/javascript" src="${ctxStatic}/jquery/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="${ctxStatic}/layui-v2.2.45/layui/layui.js"></script>
<!-- build:js -->
<script type="text/javascript" src="${ctx}/script/common/common.js"></script>
<script type="text/javascript" src="${ctx}/script/common/util.js"></script>
<!-- endbuild -->
<script type="text/javascript" src="${ctxStatic}/cos-js-sdk-v4-master/dist/cos-js-sdk-v4.js"></script>
<script src="${ctxStatic}/lrz/lrz.bundle.js"></script>
<script src="${ctx}/script/upload/cosUploadUtil.js"></script>
<script>
    var element, layer, cosUtil, mainApp, cosUtilImg;
    $(function () {
        layui.use(['element', 'layer'], function () {
            element = layui.element;
            layer = layui.layer;
        });
        cosUtil = new CosUtil({
            selectFiles: [],
            mainFolder: '/${sessionScope.newCurrentUser.id}/video/',
            bucketType: 1,// 0: 图片, 1: 文件
            insertOnly: 0,//insertOnly==0 表示允许覆盖文件 1表示不允许
            fileMaxSize: 200 * 1024 * 1024,
            onSelect: function (files) {
                var that = this;
                var filterFiles = [], now = new Date();
                that.selectFiles = [];
                for (var i = 0, file; file = files[i]; i++) {
                    var fileName = file.name;
                    var size = file.size;
                    if (size > that.fileMaxSize) {
                        util.layerMsgError('视频大小不能超过200mb');
                    } else {
                        var result = false; // true 存在 false 不存在
                        $.ajaxSettings.async = false;
                        $.get("${ctx}/file/video/getVideoResource.do", {name: fileName, size: size}, function (res) {
                            result = res.data;
                        })
                        $.ajaxSettings.async = true;
                        if (result) {
                            util.layerMsgError('视频已存在，不能上传相同的视频');
                        } else {
                            file.id = now.getTime() + i;
                            file.suffix = fileName.substring(fileName.lastIndexOf('.'));
                            filterFiles.push(file);
                            that.selectFiles.push(file);
                            $('#progress_list').append(mainApp.getProgressTpl(file, '1%'));
                        }
                    }
                }
                if (filterFiles.length > 0) {
                    mainApp.saveFiles = [];
                    $('#progress_list').parent().show();
                    cosUtil.uploadFile(filterFiles, true);
                }
            },
            onSuccess: function (file, ret) {
                var that = this;
                var data = ret.data;
                mainApp.saveFiles.push({
                    name: file.name,
                    suffix: file.suffix,
                    createBy: '${sessionScope.newCurrentUser.id}',
                    type: mainApp.bizType,
                    path: data.access_url,
                    size: file.resizeSize || file.size
                });
            },
            onProgress: function (file, ret) {
                console.log('onProgress', arguments);
                if (ret < 1) {
                    element.progress('progress_' + file.id, parseInt(ret * 100) + '%');
                } else {
                    element.progress('progress_' + file.id, '100%');
                    setTimeout(function () {
                        $('#progress_' + file.id).remove();
                    }, 1000);
                }
            },
            onFailure: function () {

            },
            onComplete: function () {
                $('#progress_list').parent().hide();
                mainApp.saveImgs();
            }
        }).init();

        cosUtilImg = new CosUtil({
            mainFolder: '/${sessionScope.newCurrentUser.id}/image/videoPoster/',
            isGetExif: false,
            onSelect: function (files) {

            },
            onSuccess: function (file, ret) {
                var that = this;
                var data = ret.data;
                mainApp.saveImage.push({
                    posterUrl: data.access_url.replace('file', 'image'),
                    id: file.id
                });
            },
            onProgress: function (file, ret) {

            },
            onFailure: function () {

            },
            onComplete: function () {
                mainApp.updatePosterUrl();
            }
        }).init();


        mainApp = {
            listContext: '',
            page: 1,
            pageSize: 24,
            noMoreData: false, // 用于判断列表是否还有数据
            dataBack: true,// 列表异步数据是否已经返回，用于阻塞scroll事件
            saveFiles: [],
            saveImage: [],
            min: '${min}' || 1, // 至少选择视频数
            max: '${max}' || 100,// 最多可选视频数
            bizType: '${type}',//业务类型
            selIds: {},
            selCount: 0,
            // 获取用户图片目录
            getFolderList: function () {
                var that = this;
                mainApp.dataBack = false;
                txz.ajaxRequest({
                    url: '${ctx}/file/video/api/list.do',
                    params: {
                        createBy: '${sessionScope.newCurrentUser.id}',
                        pageNo: that.page,
                        limit: that.pageSize
                    },
                    callBack: function (ret) {
                        mainApp.dataBack = true;
                        if (!ret.page.hasNextPage) {
                            mainApp.noMoreData = true;
                        }
                        if (that.page === 1) {
                            $('.img-list').html('');
                        }
                        for (var i = 0; i < ret.data.length; i++) {
                            var item = ret.data[i];
                            /*var resource_path = item.path;
                            var iAppid = resource_path.split('/')[1], iBucket = resource_path.split('/')[2];
                            var source_url = 'http://' + iBucket + '-' + iAppid + '.cos' + cosUtil.opt.region + '.myqcloud.com' + resource_path.replace('/' + iAppid + '/' + iBucket, '');
                            item.source_url = source_url;
                            item.resource_path = resource_path;*/
                            $('.img-list').append(mainApp.getImgTpl(item));
                            if (util.isValid(item.posterUrl)) {
                                videojs('video_' + item.id, {
                                    controls: true,
                                    height: 200
                                });
                            }
                        }
                    }
                })
            },
            getPoster: function (posterUrl, filename, id) {
                if (posterUrl == '') {
                    try {
                        var video = document.getElementById('video_' + id);
                        var canvas = document.createElement("canvas");
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        var ctx = canvas.getContext('2d');
                        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                        var url = canvas.toDataURL('image/jpeg');//第二个参数指图片质量
                        var file = mainApp.dataURLtoFile(url, filename);
                        console.info(file.name);

                        var filterFiles = [];

                        file.id = id;
                        file.suffix = '.jpg';
                        filterFiles.push(file);
                        cosUtilImg.uploadImg(filterFiles);


                        $("img").attr('src', url);
                    } catch (e) {
                        console.info(e);
                    }
                }
            },
            dataURLtoFile: function (dataurl, filename) {
                var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {type: mime});
            },
            getImgTpl: function (item, file) {
                var access_url = item.path;
                var cdnPath = '';
                if (file == null) {
                    cdnPath = access_url;
                }
                var id = item.id || '';
                var posterUrl = item.posterUrl || '';
                var filename = item.name || '';
                var preload = util.isValid(posterUrl) ? 'none' : 'auto';
                var crossOrigin = posterUrl != '' ? '' : 'crossorigin="anonymous"';
                crossOrigin = '';
                var tpl = '<li class="video-item v_item_' + id + '" data-id="' + id + '" data-url="' + access_url + '" data-poster="' + posterUrl + '">' +
                    '       <div class="pic-box">' +
                    '           <video id="video_' + id + '" src="' + cdnPath + '" ' + crossOrigin + ' x5-playsinline="" playsinline="" webkit-playsinline=""  class="video-js vjs-default-skin vjs-big-play-centered" controls preload="' + preload + '" poster="' + posterUrl + '" onloadeddata="mainApp.getPoster(\'' + posterUrl + '\',\'' + filename + '\',\'' + id + '\')">' +
                    '               <source src="' + cdnPath + '" type="video/mp4"></source>' +
                    '           </video>' +
                    '           <div class="status-mask">\n' +
                    '               <div class="sel-inner"><i class="iconfont icon-check"></i></div>' +
                    '           </div>' +
                    '       </div>';
                        if (!util.isValid(posterUrl)) {
                            tpl +=
                    '       <div style="margin: 0px auto;">' +
                    '           <div class="pic-name ellipsis-1" style="display: inline-block;\n' +
                                '    width: auto; margin-right: 5px; max-width: 80%;">' + filename + '</div>' +
                    '           <div class="video-item-delete" onclick="deleteItem(\'' + id + '\')" style="display: inline-block;' +
                                '    padding: 2px 0px; color: red; vertical-align: top;">删除</div>' +
                                '<p style="clear: both"></p>' +
                    '       </div>' ;
                        } else {
                            tpl +=
                    '       <div>' +
                    '           <div class="pic-name ellipsis-1">' + filename + '</div>' +
                    '       </div>' ;
                        }
                    tpl +='  </li>';
                return tpl;
            },
            getProgressTpl: function (file, persent) {
                var tpl = ' <li class="upload-item" id="progress_' + file.id + '">\n' +
                    '     <div class="upload-name ellipsis-1">' + file.name + '</div>\n' +
                    '     <div class="upload-progress">\n' +
                    '         <div class="layui-progress" lay-filter="progress_' + file.id + '">\n' +
                    '             <div class="layui-progress-bar layui-bg-red" lay-percent="' + persent + '"></div>\n' +
                    '         </div>\n' +
                    '     </div>\n' +
                    ' </li>'
                return tpl;
            },
            // 入库
            saveImgs: function () {
                var that = this;
                txz.ajaxRequest({
                    url: '${ctx}/file/video/api/save.do',
                    params: {
                        imgs: JSON.stringify(that.saveFiles)
                    },
                    callBack: function (ret) {
                        if (ret.success) {
                            mainApp.page = 1;
                            mainApp.noMoreData = false;
                            // mainApp.getFolderList();

                            for (var j = 0; j < ret.data.length; j++) {
                                var fileData = ret.data[j];
                                var item = {
                                    id: fileData.id,
                                    name: fileData.name,
                                    path: fileData.path
                                };

                                var videoLength = $(".img-list").find(".video-item").length;
                                if (videoLength == 0) {
                                    $(".img-list").append(mainApp.getImgTpl(item, cosUtil.opt.selectFiles[j]));
                                } else {
                                    $(".img-list").children(".video-item:first-child").before(mainApp.getImgTpl(item, cosUtil.opt.selectFiles[j]));
                                }
                                document.getElementById('video_' + fileData.id).src = window.URL.createObjectURL(cosUtil.opt.selectFiles[j]);
                            }

                            console.log('入库成功');
                        } else {
                            console.error('入库失败');
                        }
                    }
                })
            },
            // 更新posterUrl
            updatePosterUrl: function () {
                var that = this;
                console.info('1111' + JSON.stringify(that.saveImage));
                txz.ajaxRequest({
                    url: '${ctx}/file/video/api/updatePoster.do',
                    params: {
                        videos: JSON.stringify(that.saveImage)
                    },
                    callBack: function (ret) {
                        if (ret.success) {
                            mainApp.page = 1;
                            mainApp.noMoreData = false;
                            console.log('入库成功');

                            for (var i = 0; i < that.saveImage.length; i++) {
                                var item = that.saveImage[i];
                                var isRender = item.isRender;
                                if (true != isRender) {
                                    var $oldItem = $('.img-list').find(".v_item_" + item.id);
                                    var url = $oldItem.data('url');
                                    var name = $oldItem.find('.pic-name').text();

                                    var newItem = {
                                        id: item.id,
                                        name: name,
                                        posterUrl: item.posterUrl,
                                        path: url
                                    };
                                    var $prevItem = $oldItem.prev("li");
                                    var $nextItem = $oldItem.next("li");
                                    var index = $oldItem.index();
                                    $oldItem.remove();

                                    var videoLength = $(".img-list").find(".video-item").length;
                                    if (videoLength == 0) {
                                        $(".img-list").append(mainApp.getImgTpl(newItem));
                                    } else if (index == 0) {
                                        $nextItem.before(mainApp.getImgTpl(newItem));
                                    } else {
                                        $prevItem.after(mainApp.getImgTpl(newItem));
                                        // $(".img-list").children(".video-item:first-child").before(mainApp.getImgTpl(newItem));
                                    }
                                    videojs('video_' + item.id, {
                                        controls: true,
                                        height: 200
                                    });
                                    that.saveImage[i].isRender = true;
                                }
                            }

                        } else {
                            console.error('入库失败');
                        }
                    }
                })
            },
            init: function () {
                txz.toBtmListener(function (ret) {
                    if (!mainApp.noMoreData && mainApp.dataBack) {
                        ++mainApp.page;
                        // mainApp.getFolderList();
                    }
                }, 100);
                mainApp.getFolderList();
                $('#upload_btn').on('click', function () {
                    $('#upload_input').off('change').on('change', function (e) {
                        cosUtil.opt.onSelect(e.target.files);
                        $('#form')[0].reset();
                        return false;
                    });
                    setTimeout(function () {
                        $('#upload_input').click();
                    }, 0);
                    return false;
                });
                $('.img-list').on('click', '.pic-name', function (e) {
                    var $item = $(e.target).closest('.video-item');
                    if ($item.hasClass('selected')) {
                        $item.removeClass('selected');
                        delete mainApp.selIds[$item.data('id')];
                        --mainApp.selCount;
                    } else {
                        var poster = $item.data('poster');
                        if (!util.isValid(poster)) {
                            top.layer.confirm('该视频首屏图截取失败，确认要选中吗？', {
                                icon: 3,
                                title: '系统提示'
                            }, function (index) {
                                top.layer.close(index);
                                if (mainApp.selCount === parseInt(mainApp.max)) {
                                    util.layerMsgError('最多只能选择' + mainApp.max + '个视频');
                                    return;
                                }
                                $item.addClass('selected');
                                mainApp.selIds[$item.data('id')] = true;
                                ++mainApp.selCount;
                            });
                        } else {
                            if (mainApp.selCount === parseInt(mainApp.max)) {
                                util.layerMsgError('最多只能选择' + mainApp.max + '个视频');
                                return;
                            }
                            $item.addClass('selected');
                            mainApp.selIds[$item.data('id')] = true;
                            ++mainApp.selCount;
                        }
                    }
                });
            }
        };
        mainApp.init();
    })

    function validate() {
        if (mainApp.selCount < parseInt(mainApp.min)) {
            util.layerMsgError('请至少选择' + mainApp.min + '个视频');
            return false;
        }
        return true;
    }

    function close() {
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);
    }

    function randomn(n) {
        let res = ''
        for (; res.length < n; res += Math.random().toString(36).substr(2).toLowerCase()) {
        }
        return res.substr(0, n)
    }

    function getImgs() {
        var selImgs = [];
        var backType = '${backType}';
        for (var attr in mainApp.selIds) {
            var $item = $('.video-item[data-id=' + attr + ']');

            function getHtmlStr(item) {
                var random = randomn(15);
                var array = new Array();
                if (backType == 'iframe') {
                    array.push("<iframe class='video_iframe_" + item.id + "' width='400' height='320' data-path='" + item.path + "' data-poster='" + item.poster + "' data-id='" + item.id + "' data-random='" + random + "' allowfullscreen='true' frameborder='0' src='${ctx}/file/video/iframePage.do?id=" + item.id + "'></iframe>");
                } else if (backType == 'video') {
                    array.push("<video class='video-js vjs-default-skin vjs-big-play-centered' style='width:100%' id='video_" + random + "' controls='' preload='none' x5-playsinline='' playsinline='' webkit-playsinline='' poster='" + item.poster + "'><source src='" + item.path + "' type='video/mp4'></video>");
                }
                return array.join('');
            }

            var file = {
                path: $item.data('url'),
                id: $item.data('id'),
                poster: $item.data('poster')
            }
            file.htmlStr = getHtmlStr(file);
            selImgs.push(file);
        }
        return selImgs;
    }

    function deleteItem(itemId) {
        top.layer.confirm('确定要删除该视频吗?', function (index) {
            $.post("${ctx}/file/video/api/del.do", {id: itemId}, function (res) {
                if (res.success) {
                    $(".v_item_" + itemId).remove();
                    top.layer.close(index);
                } else {
                    util.layerMsgError('删除失败');
                }
            })
        })
    }
</script>
</body>
</html>